// pages/index/details/index.js
const $api = require('../../../../request/api').API;
import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import { clearAlertRefresh } from '../../../../utils/hooks';

const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 呼叫器id
    beeperId: '',
    // 设备id
    equipId: '',
    equipMac: '',
    //--------------------------------------------------------------
    phone: '',
    linkName: '',
    address: '',
    phoneTwo: '',
    houseNumber: '',
    provinceName: '',
    cityName: '',
    areaName: '',
    streetName: '',
    villageName: '',
    callingName: '',
    equipNickName: '',
    installArea: '',
    equipCode: '',
    flowEndDate: '',
    callingStatus: 0,
		callingErrorStatus: 0,
		equipPhone:'',
    money: 0,
    wxAppUrl: '',
    asrSwitch: [],
    asrSwitch1: 0,
    asrSwitch2: 0,
    asrSwitch3: 0,
    // 服务列表
    serviceList: [],
    // 是否为主用户
    mainFlag: 0,
    // 修改昵称或者安装区域弹框
    showUpdateData: false,
    showType: 1, //1代表昵称修改 2代表安装区域修改
    tempData: '', //临时数据，用来修改昵称和安装区域
    // 经纬度
    latitude: '',
    longitude: '',
    voiceShow: false,
    voiceTitle: 1,
    // 类型
    beeperType: '',
    beeperVersion: '',
    powerLevel: '',
    showBeeperQrcode: false,
    defaultOpen: '',
    content: 1,
    markers: [
      {
        id: 1,
        longitude: 0,
        latitude: 0,
        width: 26,
        height: 30
      }
    ],
    markersInfo: {
      address: '',
      areaName: '',
      cityName: '',
      createDate: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let id = options.beeperId;
    if (id != undefined) {
      this.setData({
        beeperId: options.beeperId
      });
    }
  },

  // 请求数据
  getData(id) {
    let params = {
      id: id ? id : this.data.beeperId
    };
    $api
      .getBeeper(params)
      .then(res => {
        if (res.data.status === 0) {
          var data = res.data.data;
          this.setData({
            beeperId: data.beeperId,
            equipId: data.equipId,
						phone: data.phone,
						equipPhone:data.equipPhone,
            linkName: data.linkName,
            address: data.address === '待补充' ? '' : data.address,
            houseNumber: data.houseNumber,
            provinceName: data.provinceName,
            equipNickName: data.equipNickName,
            phoneTwo: data.phoneTwo,
            installArea: data.installArea,
            equipCode: data.equipCode,
            flowEndDate: data.flowEndDate == null ? '' : data.flowEndDate,
            cityName: data.cityName,
            areaName: data.areaName,
            streetName: data.streetName,
            villageName: data.villageName,
            callingName: data.equipName,
            callingStatus: data.equipState,
            money: data.balance,
            mainFlag: data.mainFlag,
            latitude: data.latitude,
            longitude: data.longitude,
            beeperType: data.beeperType,
            beeperVersion: data.beeperVersion,
            powerLevel: data.powerLevel,
            wxAppUrl: data.wxAppUrl,
            defaultOpen: data.defaultOpen,
            callingErrorStatus: data.errorState,
            equipMac: data.equipMac,
            content: data.asrSwitch.split('')[0],
            asrSwitch1: Number(data.asrSwitch.split('')[1]),
            asrSwitch2: Number(data.asrSwitch.split('')[2]),
            asrSwitch3: Number(data.asrSwitch.split('')[3])
          });
          app.globalData.serviceList = data.beeperBtnList;
          this.getLocationData();
        }
      })
      .catch(err => {
        console.log(err);
      });
  },

  // 去设置紧急联系人
  toUrgentContact() {
    wx.navigateTo({
      url: '/subcontract/equipment/pages/urgentContact/index?equipId=' + this.data.equipId + '&equipType=2'
    });
  },
  // 通讯录
  toAddressBook() {
    wx.navigateTo({
      url: '/subcontract/equipment/pages/beeperContacts/index?equipId=' + this.data.equipId + '&equipType=2'
    });
  },

  //是否开启语音识别
  openVoice() {
    this.setData({
      voiceShow: true,
      voiceTitle: 1
    });
  },

  //设置低电提醒
  setPowerRemind() {
    this.setData({
      voiceShow: true,
      voiceTitle: 2
    });
  },

  voiceRadioChange(e) {
    this.setData({
      content: e.detail.value
    });
  },

  // 解除警报
  jieAlarm() {
    Dialog.confirm({
      title: '提示',
      showCancelButton: true,
      cancelButtonText: '误触发',
      confirmButtonText: '已处理',
      closeOnClickOverlay: true,
      message: '确定解除警报吗？'
    })
      .then(() => {
        this.handleAlarmLiftedProcess();
      })
      .catch(() => {
        this.handleFalseAlarmRelease();
      });
  },

  /**
   * 解除警报 - 已处理
   */
  handleAlarmLiftedProcess() {
    $api
      .equipAllClear({
        equipId: this.data.equipId,
        cancelReason: 2
      })
      .then(() => {
        wx.showToast({
          title: '解除成功！'
        });
        clearAlertRefresh(this.data.beeperId, this);
      });
  },

  /**
   * 解除警报 - 误触
   */
  handleFalseAlarmRelease() {
    $api
      .equipAllClear({
        equipId: this.data.equipId,
        cancelReason: 1
      })
      .then(() => {
        wx.showToast({
          title: '解除成功！'
        });
        clearAlertRefresh(this.data.beeperId, this);
      });
  },

  voiceCheckboxChange(e) {
    const type = e.currentTarget.dataset.type;
    let asrSwitch1 = this.data.asrSwitch1;
    let asrSwitch2 = this.data.asrSwitch2;
    let asrSwitch3 = this.data.asrSwitch3;

    if (type === 1) {
      asrSwitch1 = e.detail ? 1 : 0;
    } else if (type === 2) {
      asrSwitch2 = e.detail ? 1 : 0;
    } else {
      asrSwitch3 = e.detail ? 1 : 0;
    }
    this.setData({
      asrSwitch1,
      asrSwitch2,
      asrSwitch3
    });
  },

  closeVoice() {
    this.setData({
      voiceShow: false
    });
  },

  confirmVoice() {
    let params = {
      type: this.data.voiceTitle === 1 ? 24 : 25,
      equipCode: this.data.equipCode
    };
    if (this.data.voiceTitle === 1) {
      params = {
        ...params,
        asrSwitch: [this.data.content, this.data.asrSwitch1, this.data.asrSwitch2, this.data.asrSwitch3].join(''),
        content: [this.data.content, this.data.asrSwitch1, this.data.asrSwitch2, this.data.asrSwitch3].join('')
      };
    } else {
      params = {
        ...params,
        content: this.data.content
      };
    }
    $api.setVoice(params).then(res => {
      if (res.data.status === 0) {
        wx.showToast({
          title: '操作成功'
        });
        this.closeVoice();
        setTimeout(() => {
          this.getData(this.data.beeperId);
        }, 1000);
      } else {
        wx.showToast({
          icon: 'none',
          title: res.data.msg
        });
      }
    });
  },

  // 打开修改弹框
  openUpdateData(e) {
    let type = e.currentTarget.dataset.type;
    if (!this.data.mainFlag && type == 1) return;
    this.setData({
      showUpdateData: true,
      showType: type,
      tempData: type == 1 ? this.data.equipNickName : type == 2 ? this.data.installArea : this.data.phoneTwo
    });
  },
  // 关闭修改昵称弹框
  closeUpdateData() {
    this.setData({
      showUpdateData: false
    });
  },
  // 输入绑定
  dataInput(e) {
    let value = e.detail.value;
    this.setData({
      tempData: value
    });
  },
  // 修改昵称
  UpdateData() {
    if (!this.data.tempData && this.data.showType === 1) {
      Toast('请输入昵称');
      return;
    } else if (!this.data.tempData && this.data.showType === 2) {
      Toast('请输入安装区域');
      return;
    } else if (!this.data.tempData && this.data.showType === 3) {
      Toast('请输入备用电话');
      return;
    }
    if (this.data.showType === 3) {
      $api
        .setPhoneTwo({
          beeperId: this.data.beeperId,
          phoneTwo: this.data.tempData
        })
        .then(res => {
          if (res.data.status === 0) {
            wx.showToast({
              title: '设置成功'
            });
            this.setData({
              showUpdateData: false,
              tempData: ''
            });
            this.getData(this.data.beeperId);
          }
        })
        .catch(err => {
          console.log(err);
        });
    } else {
      let params = {
        id: this.data.equipId,
        name: this.data.tempData,
        state: this.data.showType
      };
      $api
        .UpdataName(params)
        .then(res => {
          if (res.data.status === 0) {
            if (this.data.showType === 1) {
              wx.showToast({
                title: '设置昵称成功'
              });
            } else {
              wx.showToast({
                title: '设置安装区域成功'
              });
            }
            this.setData({
              showUpdateData: false
            });
            this.getData(this.data.beeperId);
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  },
  // 修改设置
  modifyDefaultOpen() {
    let { defaultOpen, mainFlag } = this.data;
    if (!mainFlag) return;
    let params = {
      id: this.data.beeperId,
      state: defaultOpen == 1 ? 2 : 1
    };
    let message = defaultOpen === 1 ? '确认修改为全部?' : '确认修改为精选';
    Dialog.confirm({
      title: '提示',
      message: message
    }).then(() => {
      $api.setDefalutOpen(params).then(res => {
        if (defaultOpen === 1) {
          this.setData({
            defaultOpen: 2
          });
          Toast.success('设置全部成功');
        } else if (defaultOpen === 2) {
          this.setData({
            defaultOpen: 1
          });
          Toast.success('设置精选成功');
        }
      });
    });
  },

  // 跳转充值页
  goTopUp() {
    wx.navigateTo({
      url: '../topUp/index?id=' + this.data.beeperId
    });
  },
  // 跳转服务列表
  toServiceList() {
    wx.navigateTo({
      url: '../serviceList/index?id=' + this.data.beeperId
    });
  },
  // 跳转用户列表
  toUserList() {
    wx.navigateTo({
      url: '../userList/index?id=' + this.data.beeperId
    });
  },
  //跳转微聊好友列表
  toFriend() {
    wx.navigateTo({
      url: '/subcontract/equipment/pages/microChat/index?beeperId=' + this.data.beeperId
    });
  },
  // 跳转报警记录列表
  toWarningRecord() {
    wx.navigateTo({
      url: '../warningRecord/index?id=' + this.data.equipId
    });
  },
  // 解绑设备
  jiebang() {
    Dialog.confirm({
      title: '提示',
      message: '确认解绑当前设备吗？'
    }).then(res => {
      let params = {
        id: this.data.equipId
      };
      $api
        .unbindBinding(params)
        .then(res => {
          if (res.data.status == 0) {
            wx.showToast({
              title: '解绑成功！'
            });
            const page = getCurrentPages().at(-2);
            const callingList = page.data.callingList;
            const index = page.data.callingList.findIndex(item => item.relationId == this.data.beeperId);
            if (index != -1) {
              callingList.splice(index, 1);
              page.setData({
                callingList
              });
            }
            setTimeout(() => {
              wx.switchTab({
                url: '/pages/equipment/index'
              });
            }, 1000);
          }
        })
        .catch(err => {
          console.log('解绑设备', err);
        });
    });
  },
  toOrder() {
    app.globalData.beeperOrderId = this.data.beeperId;
    wx.switchTab({
      url: '/pages/order/index'
    });
  },
  // 显示呼叫器二维码
  showBeeperQrcodePopup() {
    this.setData({
      showBeeperQrcode: true
    });
  },
  // 关闭呼叫器二维码
  closeBeeperQrcodePopup() {
    this.setData({
      showBeeperQrcode: false
    });
  },
  // 去呼叫器地址页面
  toBeeperAddress() {
    wx.navigateTo({
      url: '/subcontract/person/pages/beeperAddress/index?id=' + this.data.beeperId
    });
  },

  //立即定位
  openLocation() {
    const params = {
      equipId: this.data.equipId
    };
    $api
      .beeperOpenLocation(params)
      .then(res => {
        if (res.data.status === 0) {
          Toast.success('操作成功');
          this.getData(this.data.beeperId);
        } else {
          Toast.fail(res.data.msg);
        }
      })
      .catch(err => {
        Toast.fail(err.msg);
      });
  },

  //获取最新一条定位数据
  getLocationData() {
    const params = {
      equipId: this.data.equipId
    };
    $api.getFootprint(params).then(res => {
      if (res.data.data != null) {
        const { latitude, longitude, address, areaName, cityName, createDate } = res.data.data;
        this.setData({
          'markers[0].latitude': Number(latitude),
          'markers[0].longitude': Number(longitude),
          'markersInfo.address': address,
          'markersInfo.areaName': areaName,
          'markersInfo.cityName': cityName,
          'markersInfo.createDate': createDate
        });
      }
    });
  },

  toDetail() {
    const { beeperId } = this.data;
    wx.navigateTo({
      url: '/subcontract/equipment/pages/details/index?beeperId=' + beeperId
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getData(this.data.beeperId);
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
});
